<?php
// $Id$

/**
 * Controller_Prepare 控制器
 */
class Controller_Prepare extends Controller_Abstract
{
    /**
     * traffic 准备数据
     */
    private $myTraffic;

    /**
     * 数据表 date 字段
     * 表示为 2009-05-13
     * 唯一索引：t_hit_by_date
     * 一般索引：其他6张表
     *
     * @var string / date('Y-m-d')
     */
    private $today;

    /**
     * 准备用控制器，每次请求都会调用
     *
     * @session 初始化(不影响旧访问者)
     * @trafficFlow 该功能可被关闭，影响变量：QTrafficFlowEnabled (boolean)
     * 用于详细统计访问信息
     * NOTICE : 除 __contruct 可由其他控制器调用外，所有其他具体实现自身外不可调用
     * NOTICE : 私有方法不以 'action' 开头
     */
    public function __construct()
    {
        parent::__construct(NULL);

        /**
         * 初始化 session
         *
         * @_var $_SESSION
         */
        $this->QSessionInitiate();
        
        /**
         * Module Traffic
         * 流量统计，数据来源 Helper_Traffic->getTraffic()
         * 
         * @var array
         */
        if(Q::ini('appini/module_traffic_enabled') == 1)
        {
            $this->today = date('Y-m-d', $_SERVER['REQUEST_TIME']);
            $obj = new Helper_Traffic();
            $this->myTraffic = $obj->getMyTraffic();
            $this->QTrafficFlow();
        }
    }

    /**
     * session 初始化操作
     *
     * @var array $_SESSION
     */
    private function QSessionInitiate()
    {
        if(!isset($_SESSION['lrole']))
        {
            $_SESSION['lrole']    = 410;
            $_SESSION['lrole_id'] = -1;
            $_SESSION['notice']   = '<a href="'.url('siteinfo/index').'">使用帮助</a>';
        }
    }

    /**
     * QTrafficFlow __defined at May 14th
     *
     * 通过全局变量控制流量表
     *
     * @safe-param $_SERVER
     *
     * 记录流量
     */
    private function QTrafficFlow()
    {
        /**
         * 浏览器类型统计(按天算)
         * bug目前发现许多浏览器(t-broswer-)标识无法识别，需要调整
         *
         * 涉及表:
         * t_browser_by_date
         * t_unknown_browser_by_date
         */
        $this->analyzeBrowser();

        /**
         * 链接流行度统计(按天算)
         *
         * 涉及表:
         * t_uri_by_date
         */
        $this->analyzeURI();

        /**
         * ip访问(按天算)
         *
         * 涉及表:
         * t_ip_by_date
         */
        $this->analyzeIP();

        /**
         * 来源(按天算)
         *
         * 涉及表:
         * t_referer_by_date
         */
        $this->analyzeReferer();

        /**
         * 时间段(按天算)
         *
         * 涉及表:
         * t_hour
         */
        $this->analyzeHour();

        /**
         * 点击(按天算)
         *
         * 涉及表:
         * t_hit_by_date
         */
        $this->analyzeHit();
    }

    /**
     * 获取浏览器类型
     * Cron: 获得浏览器使用频率的总体分布
     *
     * 涉及表:
     * t_browser_by_date
     * t_unknown_browser_by_date
     */
    private function analyzeBrowser()
    {

        /**
         * 类型已知 case : 1
         * 类型未知 case : 0
         */
        switch($this->myTraffic['onList'])
        {
            case 1 :

                // 类型已知，测试是否存在，日期date与类型browser
                $browserExistence = TBrowser::find('date = ? AND browser = ?', $this->today, $this->myTraffic['identifier'])->query();

                // 类型已知，记录不存在，新建
                if($browserExistence->id == '')
                {
                    $newBrowserRecord = new TBrowser(array(
                        'date'    => $this->today,
                        'browser' => $this->myTraffic['identifier'],
                        'hits'    => 1
                    ));
                    $newBrowserRecord->save();
                }

                // 类型已知，记录存在，更新
                else
                {
                    $browserExistence->hits += 1;
                    $browserExistence->save();
                }

                break;

            case 0 :

                // 类型未知，测试是否存在，日期date与类型browser_identifier
                $browserExistence = TUnknownBrowser::find('date = ? AND browser_identifier = ?', $this->today, $this->myTraffic['identifier'])->query();

                // 类型未知，记录不存在，新建
                if($browserExistence->id == '')
                {
                    $newUnknownBrowserRecord = new TUnknownBrowser(array(
                        'date'               => $this->today,
                        'browser_identifier' => $this->myTraffic['identifier'],
                        'hits'               => 1
                    ));
                    $newUnknownBrowserRecord->save();
                }

                // 类型未知，记录存在，更新
                else
                {
                    $browserExistence->hits += 1;
                    $browserExistence->save();
                }

                break;
        }
    }

    /**
     * 获取请求链接
     * Cron: 生成一周(date - date)内 XX栏目 被搜索前三多的关键字报告
     *
     * 涉及表:
     * t_uri_by_date
     */
    private function analyzeURI()
    {
        // 测试当前记录是否存在，日期date与类型uri
        $uriExistence = TUri::find('date = ? AND uri = ?', $this->today, $this->myTraffic['uri'])->query();

        if($uriExistence->id == '')
        {
            $newUriRecord = new TUri(array(
                'date' => $this->today,
                'uri'  => $this->myTraffic['uri'],
                'hits' => 1
            ));
            $newUriRecord->save();
        }
        else
        {
            $uriExistence->hits += 1;
            $uriExistence->save();
        }
    }

    /**
     *
     * 涉及表:
     * t_ip_by_date
     */
    public function analyzeIP()
    {
        $ipExistence = TIp::find('date = ? AND ip = ?', $this->today, $this->myTraffic['ip'])->query();

        if($ipExistence->id == '')
        {
            $newIpRecord = new TIp(array(
                'date' => $this->today,
                'ip'   => $this->myTraffic['ip'],
                'hits' => 1
            ));
            $newIpRecord->save();
        }
        else
        {
            $ipExistence->hits += 1;
            $ipExistence->save();
        }
    }

    /**
     * 地址来源信息
     * Cron: 获得主要访问途径的分布比率
     *
     * 涉及表:
     * t_referer_by_date
     */
    private function analyzeReferer()
    {
        $refererExistence = TReferer::find('date = ? AND referer = ?', $this->today, $this->myTraffic['referer'])->query();

        if($refererExistence->id == '')
        {
            $newRefererRecord = new TReferer(array(
                'date'    => $this->today,
                'referer' => $this->myTraffic['referer'],
                'hits'    => 1
            ));
            $newRefererRecord->save();
        }
        else
        {
            $refererExistence->hits += 1;
            $refererExistence->save();
        }
    }

    /**
     * 记录访问时间
     * Cron: 获得访问者访问的时间段的总体分布
     *
     * 涉及表:
     * t_hour
     */
    private function analyzeHour()
    {
        $currentHour = date('H' ,$_SERVER['REQUEST_TIME']);
        $nextHour    = date('H' ,$_SERVER['REQUEST_TIME']+3600);
        $hour = $currentHour . ':00 - ' . $nextHour . ':00';

        $hourExistence = THour::find('hour = ?', $hour)->query();

        $hourExistence->hits += 1;
        $hourExistence->save();
    }

    /**
     * 获取点击率
     * Cron: 获得点击率
     *
     * 涉及表:
     * t_unknown_browser_by_date
     */
    public function analyzeHit()
    {
        $hitExistence = THit::find('date = ?', $this->today)->query();

        if($hitExistence->id == '')
        {
            $newHitRecord = new THit(array(
                'date'  => $this->today,
                'week'  => $this->myTraffic['firstDayOfWeek'].' - '.$this->myTraffic['lastDayOfWeek'],
                'month' => date('m', $_SERVER['REQUEST_TIME']),
                'hits'  => 1
            ));            
            $newHitRecord->save();
        }
        else
        {
            $hitExistence->hits += 1;
            $hitExistence->save();
        }
    }
}